﻿using ldc_mvc_closing_hwk.Models.ApiModel;
using ldc_mvc_closing_hwk.Models.Database;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ldc_mvc_closing_hwk.Controllers
{
    [ApiController]
    [Route("api/[action]")]
    public class ApiController : Controller
    {
        private readonly LdcFASContext _db;

        public ApiController(LdcFASContext db)
        {
            _db = db;
        }

        public IActionResult List(int page, int limit)
        {
            var skip = (page - 1) * limit;

            var allCount = _db.ArticleMeta.Count();
            var articleMetaList = _db.ArticleMeta.Skip(skip).Take(limit).ToList();
            return ApiHelper.SuccessList(articleMetaList, allCount);
        }

        [HttpPost]
        public IActionResult Delete(DeleteArticleRequest deleteArticleRequert)
        {
            var articleMeta = _db.ArticleMeta;
            var articleList = articleMeta.ToList();
            var entity = articleMeta.FirstOrDefault(e => e.Id == deleteArticleRequert.Id);
            if (entity == null)
            {
                return ApiHelper.ErrorDelete($"试图删除空列: id={deleteArticleRequert.Id}");
            }
            articleMeta.Remove(entity);
            if (!(_db.SaveChanges() > 0))
            {
                return ApiHelper.ErrorDelete($"删除失败");
            }

            return ApiHelper.Success();
        }

        [HttpPost]
        public IActionResult DeleteList(List<DeleteArticleRequest> deleteArticleRequertList)
        {
            var articleMeta = _db.ArticleMeta;
            var articleList = articleMeta.ToList();
            var error = new StringBuilder();
            foreach (var item in deleteArticleRequertList)
            {
                var entity = articleMeta.FirstOrDefault(e => e.Id == item.Id);
                if (entity == null)
                {
                    error.AppendLine($"[id={item.Id}]试图删除空列");
                }
                articleMeta.Remove(entity);
                if (!(_db.SaveChanges() > 0))
                {
                    error.AppendLine($"[id={item.Id}]删除失败");
                }
            }

            var eroMsg = error.ToString();
            if (!string.IsNullOrEmpty(eroMsg))
            {
                return ApiHelper.ErrorDelete(eroMsg);
            }

            return ApiHelper.Success();
        }
    }
}
